document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const sqlFileInput = document.getElementById('sqlFileInput');
  const sqlInput = document.getElementById('sqlInput');
  const parseButton = document.getElementById('parseButton');
  const resultSection = document.getElementById('resultSection');
  const tableResult = document.getElementById('tableResult');
  const generateDocButton = document.getElementById('generateDocButton');
  
  // 获取列选择的复选框
  const colFieldName = document.getElementById('col-field-name');
  const colType = document.getElementById('col-type');
  const colNullable = document.getElementById('col-nullable');
  const colKey = document.getElementById('col-key');
  const colDefault = document.getElementById('col-default');
  const colComment = document.getElementById('col-comment');
  
  // 获取全选/全不选按钮
  const selectAllColumnsButton = document.getElementById('selectAllColumnsButton');
  const unselectAllColumnsButton = document.getElementById('unselectAllColumnsButton');
  
  // 存储解析后的多张表信息
  let parsedTableInfos = [];
  
  // 监听文件上传
  sqlFileInput.addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(e) {
        sqlInput.value = e.target.result;
      };
      reader.readAsText(file);
    }
  });
  
  // 监听解析按钮点击
  parseButton.addEventListener('click', function() {
    const sqlContent = sqlInput.value.trim();
    if (!sqlContent) {
      alert('请上传SQL文件或输入SQL语句！');
      return;
    }
    
    try {
      // 解析可能包含多张表的 SQL
      parsedTableInfos = parseCreateTableSQL(sqlContent);
      
      if (parsedTableInfos && parsedTableInfos.length > 0) {
        // 显示解析结果
        displayTableInfo(parsedTableInfos);
        resultSection.style.display = 'block';
      } else {
        alert('未能识别有效的CREATE TABLE语句');
      }
    } catch (error) {
      console.error('解析SQL出错:', error);
      alert('SQL解析失败: ' + error.message);
    }
  });
  
  // 监听全选按钮点击
  selectAllColumnsButton.addEventListener('click', function() {
    toggleAllColumnCheckboxes(true);
  });
  
  // 监听全不选按钮点击
  unselectAllColumnsButton.addEventListener('click', function() {
    toggleAllColumnCheckboxes(false);
  });
  
  // 全选或全不选所有列
  function toggleAllColumnCheckboxes(checked) {
    const columnCheckboxes = [
      colFieldName,
      colType,
      colNullable,
      colKey,
      colDefault,
      colComment
    ];
    
    columnCheckboxes.forEach(checkbox => {
      if (checkbox) {
        checkbox.checked = checked;
      }
    });
  }
  
  // 监听生成Word文档按钮点击
  generateDocButton.addEventListener('click', function() {
    if (!parsedTableInfos || parsedTableInfos.length === 0) {
      alert('请先解析SQL语句！');
      return;
    }
    
    try {
      // 获取用户选择的列
      const selectedColumns = getSelectedColumns();
      
      // 检查是否至少选择了一个列
      if (!selectedColumns.length) {
        alert('请至少选择一个列！');
        return;
      }
      
      // 生成多张表的文档
      generateWordDocument(parsedTableInfos, selectedColumns);
    } catch (error) {
      console.error('生成Word文档出错:', error);
      alert('生成Word文档失败: ' + error.message);
    }
  });
  
  // 获取选中的列
  function getSelectedColumns() {
    const selectedColumns = [];
    
    if (colFieldName.checked) selectedColumns.push({ id: 'columnName', title: '字段名' });
    if (colType.checked) selectedColumns.push({ id: 'dataType', title: '类型' });
    if (colNullable.checked) selectedColumns.push({ id: 'isNullable', title: '是否为空' });
    if (colKey.checked) selectedColumns.push({ id: 'keyType', title: '索引' });
    if (colDefault.checked) selectedColumns.push({ id: 'defaultValue', title: '默认值' });
    if (colComment.checked) selectedColumns.push({ id: 'comment', title: '说明' });
    
    return selectedColumns;
  }
});

/**
 * 解析CREATE TABLE SQL语句
 * @param {string} sql - SQL语句
 * @returns {Array<Object>} 表信息对象数组
 */
function parseCreateTableSQL(sql) {
  // 使用SQLParser库解析SQL，支持多张表
  return SQLParser.parseCreateTables(sql);
}

/**
 * 显示表信息
 * @param {Array<Object>} tableInfos - 表信息对象数组
 */
function displayTableInfo(tableInfos) {
  if (!Array.isArray(tableInfos)) {
    tableInfos = [tableInfos];
  }
  
  let html = '';
  tableInfos.forEach((tableInfo, tableIndex) => {
    if (tableIndex > 0) {
      html += '<hr/>'; // 分隔不同表
    }
    html += generateSingleTableHTML(tableInfo, tableIndex);
  });
  
  tableResult.innerHTML = html;
}

// 生成单张表的HTML
function generateSingleTableHTML(tableInfo, tableIndex) {
  // 创建表格显示解析结果
  const displayName = tableInfo.comment || tableInfo.tableName;
  let html = `<h3>表名: ${displayName}</h3>`;
  
  // 如果有表注释，显示表注释
  if (tableInfo.comment) {
    html += `<p>表说明: ${tableInfo.comment}</p>`;
  }
  
  html += `<table class="three-line-table">
    <tr>
      <th>字段名</th>
      <th>类型</th>
      <th>是否为空</th>
      <th>索引</th>
      <th>默认值</th>
      <th>说明</th>
    </tr>`;
  
  // 确保所有列都正确显示
  if (tableInfo.columns && tableInfo.columns.length > 0) {
    tableInfo.columns.forEach((column, columnIndex) => {
      html += `<tr>
        <td>${column.columnName || ''}</td>
        <td>${column.dataType || ''}</td>
        <td>${column.isNullable || ''}</td>
        <td>${column.keyType || '无'}</td>
        <td>${column.defaultValue !== undefined ? column.defaultValue : '无'}</td>
        <td>${column.comment || ''}</td>
      </tr>`;
    });
  } else {
    html += `<tr><td colspan="6">未能解析出字段信息</td></tr>`;
  }
  
  html += '</table>';
  
  // 显示主键信息
  const primaryKeys = tableInfo.constraints ? tableInfo.constraints.filter(c => c.type === 'PRIMARY KEY') : [];
  if (primaryKeys.length > 0) {
    html += '<h4>主键信息</h4>';
    html += '<ul>';
    
    primaryKeys.forEach(pk => {
      html += `<li>主键: (${pk.columns.join(', ')})</li>`;
    });
    
    html += '</ul>';
  }
  
  // 显示索引信息
  const indexes = tableInfo.constraints ? tableInfo.constraints.filter(c => c.type === 'INDEX' || c.type === 'UNIQUE') : [];
  if (indexes.length > 0) {
    html += '<h4>索引信息</h4>';
    html += '<ul>';
    
    indexes.forEach(idx => {
      const idxType = idx.type === 'UNIQUE' ? '唯一索引' : '普通索引';
      html += `<li>${idxType} ${idx.name || ''}: (${idx.columns.join(', ')})</li>`;
    });
    
    html += '</ul>';
  }
  
  // 显示外键信息
  const foreignKeys = tableInfo.constraints ? tableInfo.constraints.filter(c => c.type === 'FOREIGN KEY') : [];
  if (foreignKeys.length > 0) {
    html += '<h4>外键信息</h4>';
    html += '<ul>';
    
    foreignKeys.forEach(fk => {
      let fkInfo = `<li>外键 ${fk.name || ''}: (${fk.columns.join(', ')}) 引用 ${fk.refTable}(${fk.refColumns.join(', ')})`;
      
      if (fk.onDelete) {
        fkInfo += ` ON DELETE ${fk.onDelete}`;
      }
      
      if (fk.onUpdate) {
        fkInfo += ` ON UPDATE ${fk.onUpdate}`;
      }
      
      fkInfo += '</li>';
      html += fkInfo;
    });
    
    html += '</ul>';
  }
  
  return html;
}

/**
 * 生成Word文档
 * @param {Array<Object>} tableInfos - 表信息对象数组
 * @param {Array<Object>} selectedColumns - 用户选择的列
 */
function generateWordDocument(tableInfos, selectedColumns) {
  if (!Array.isArray(tableInfos)) {
    tableInfos = [tableInfos];
  }
  
  // 创建文档
  const doc = DocxGenerator.createDocument();
  
  // 获取表头
  const headers = selectedColumns.map(col => col.title);
  
  // 对每张表分别添加表格
  tableInfos.forEach((tableInfo, idx) => {
    // 根据选择的列生成数据行
    const rows = tableInfo.columns.map(column => {
      const rowData = [];
      
      selectedColumns.forEach(col => {
        switch (col.id) {
          case 'columnName':
            rowData.push(column.columnName || '');
            break;
          case 'dataType':
            rowData.push(column.dataType || '');
            break;
          case 'isNullable':
            rowData.push(column.isNullable || '');
            break;
          case 'keyType':
            rowData.push(column.keyType || '无');
            break;
          case 'defaultValue':
            rowData.push(column.defaultValue !== undefined ? column.defaultValue : '无');
            break;
          case 'comment':
            rowData.push(column.comment || '');
            break;
          default:
            rowData.push('');
        }
      });
      
      return rowData;
    });

    DocxGenerator.addTable(doc, headers, rows, {
      threeLineStyle: true,
      tableName: tableInfo.tableName,
      tableComment: tableInfo.comment,
      constraints: tableInfo.constraints,
      tableNo: idx + 1
    });
  });
  
  // 保存文档
  const filename = '生成的表结果.docx';
  DocxGenerator.saveDocument(doc, filename)
    .then(() => {
      console.log('文档已生成:', filename);
    })
    .catch(error => {
      console.error('保存文档出错:', error);
      alert('保存文档失败: ' + error.message);
    });
} 